<template>
  <div class="home-page">

    <!-- 背景图片容器 -->
    <div class="background-image">
      <img src="@/assets/background2.jpg" alt="背景图片" />
    </div>

    <div class="animal-carousel" v-if="animalList.length > 0">

      <div class="carousel-container" ref="carouselContainer"
           @touchstart="onTouchStart"
           @touchmove="onTouchMove"
           @touchend="onTouchEnd"
           @mousedown="onMouseDown"
           @mousemove="onMouseMove"
           @mouseup="onMouseUp"
           @mouseleave="onMouseUp">
        <h2 class="section-title">热门宠物推荐</h2>
        <div class="carousel-track" ref="carouselTrack">
          <div class="carousel-item" v-for="animal in visibleAnimals" :key="animal.id" @click="viewAnimalDetail(animal.id)">
            <div class="carousel-card">
              <img :src="animal.imageUrl || 'https://via.placeholder.com/300x200?text=' + animal.name" alt="动物图片" class="carousel-image">
              <div class="carousel-info">
                <p class="animal-name">{{ animal.name }}</p>
                <p class="animal-species">{{ animal.species }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="carousel-controls">
        <button class="control-btn prev" @click="scrollToPrev" :disabled="currentSlide === 0">
          <i class="el-icon-arrow-left"></i>
        </button>
        <div class="slide-indicators">
          <span v-for="(item, index) in slideCount" :key="index"
                :class="{ 'active': index === currentSlide }"
                @click="goToSlide(index)"></span>
        </div>
        <button class="control-btn next" @click="scrollToNext" :disabled="currentSlide === slideCount - 1">
          <i class="el-icon-arrow-right"></i>
        </button>
      </div>
    </div>

    <div class="filter-section">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="物种" style="width: 140px">
          <el-select v-model="filterForm.species" placeholder="选择物种" clearable>
            <el-option label="猫咪" value="猫咪" />
            <el-option label="狗狗" value="狗狗" />
            <el-option label="兔子" value="兔子" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="性别" style="width: 140px">
          <el-select v-model="filterForm.gender" placeholder="选择性别" clearable>
            <el-option label="公" :value="0" />
            <el-option label="母" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter" :loading="loading">筛选</el-button>
          <el-button @click="resetFilter" :disabled="loading">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="animal-list" v-loading="loading">
      <el-empty v-if="animalList.length === 0 && !loading" description="暂无动物信息"></el-empty>
      <el-row :gutter="20" class="animal-row" v-else>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="animal in animalList" :key="animal.id">
          <el-card class="animal-card" shadow="hover" @click="viewAnimalDetail(animal.id)">
            <div class="animal-image">
              <img :src="animal.imageUrl || 'https://via.placeholder.com/300x200'" alt="动物图片" />
            </div>
            <div class="animal-info">
              <h3>{{ animal.name }}</h3>
              <p>物种：{{ animal.species }}</p>
              <p>性别：{{ animal.gender === 0 ? '公' : '母' }}</p>
              <p>年龄：{{ animal.age }}月</p>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div class="pagination-container" v-if="total > 0">
      <div class="number" >
        <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handlePageChange"
        />
      </div>

    </div>
  </div>
</template>

<script setup>
// ...
import { ref, reactive, onMounted, onUnmounted, computed, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { listAnimalByPageApi } from '../api/animal'

const router = useRouter()
const animalList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(8)
const loading = ref(true)

const carouselContainer = ref(null)
const carouselTrack = ref(null)
const currentSlide = ref(0)
const slideWidth = ref(0)
const isDragging = ref(false)
const startX = ref(0)
const scrollLeft = ref(0)
const slideCount = computed(() => Math.ceil(visibleAnimals.value.length / itemsPerSlide.value))
const itemsPerSlide = ref(3)

const filterForm = reactive({
  species: '',
  gender: '',
})

const visibleAnimals = computed(() => {
  return animalList.value.slice(0, 12)
})

const fetchAnimalList = async () => {
  loading.value = true
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      saleStatus: 0
    }

    if (filterForm.species) {
      params.species = filterForm.species
    }

    if (filterForm.gender !== '') {
      params.gender = filterForm.gender
    }

    const data = await listAnimalByPageApi(params)

    const records = data.records || []
    records.forEach(item => {
      if (item.adoption_status !== undefined && item.adoptionStatus === undefined) {
        item.adoptionStatus = item.adoption_status
      }
      if (item.health_status !== undefined && item.healthStatus === undefined) {
        item.healthStatus = item.health_status
      }
    })

    animalList.value = records
    total.value = data.total || 0
  } catch (error) {
    console.error('获取动物列表失败:', error)
    ElMessage.error('获取动物列表失败')
  } finally {
    loading.value = false
    initCarousel()
  }
}

const initCarousel = () => {
  nextTick(() => {
    updateSlideWidth()
    updateSlidePosition()
  })
}

const updateSlideWidth = () => {
  if (!carouselContainer.value) return
  const containerWidth = carouselContainer.value.offsetWidth
  if (containerWidth < 600) {
    itemsPerSlide.value = 1
  } else if (containerWidth < 900) {
    itemsPerSlide.value = 2
  } else {
    itemsPerSlide.value = 3
  }
  const itemWidth = carouselContainer.value.offsetWidth / itemsPerSlide.value
  slideWidth.value = itemWidth
  const items = carouselTrack.value.querySelectorAll('.carousel-item')
  items.forEach(item => {
    item.style.width = `${itemWidth}px`
  })
}

const updateSlidePosition = () => {
  if (!carouselTrack.value) return
  carouselTrack.value.style.transform = `translateX(-${currentSlide.value * slideWidth.value * itemsPerSlide.value}px)`
}

const scrollToPrev = () => {
  if (currentSlide.value > 0) {
    currentSlide.value--
    updateSlidePosition()
  }
}

const scrollToNext = () => {
  if (currentSlide.value < slideCount.value - 1) {
    currentSlide.value++
    updateSlidePosition()
  }
}

const goToSlide = (index) => {
  currentSlide.value = index
  updateSlidePosition()
}

const onTouchStart = (e) => {
  isDragging.value = true
  startX.value = e.touches[0].clientX
  scrollLeft.value = currentSlide.value * slideWidth.value * itemsPerSlide.value
}

const onTouchMove = (e) => {
  if (!isDragging.value) return
  e.preventDefault()
  const x = e.touches[0].clientX
  const walk = x - startX.value
  carouselTrack.value.style.transform = `translateX(-${scrollLeft.value - walk}px)`
}

const onTouchEnd = () => {
  isDragging.value = false
  const walk = startX.value - event.changedTouches[0].clientX
  const threshold = slideWidth.value * itemsPerSlide.value / 3

  if (walk > threshold && currentSlide.value < slideCount.value - 1) {
    currentSlide.value++
  } else if (walk < -threshold && currentSlide.value > 0) {
    currentSlide.value--
  }

  updateSlidePosition()
}

const onMouseDown = (e) => {
  isDragging.value = true
  carouselContainer.value.classList.add('grabbing')
  startX.value = e.pageX - carouselContainer.value.offsetLeft
  scrollLeft.value = currentSlide.value * slideWidth.value * itemsPerSlide.value
}

const onMouseMove = (e) => {
  if (!isDragging.value) return
  e.preventDefault()
  const x = e.pageX - carouselContainer.value.offsetLeft
  const walk = x - startX.value
  carouselTrack.value.style.transform = `translateX(-${scrollLeft.value - walk}px)`
}

const onMouseUp = () => {
  isDragging.value = false
  carouselContainer.value.classList.remove('grabbing')

  const walk = startX.value - (event.pageX - carouselContainer.value.offsetLeft)
  const threshold = slideWidth.value * itemsPerSlide.value / 3

  if (walk > threshold && currentSlide.value < slideCount.value - 1) {
    currentSlide.value++
  } else if (walk < -threshold && currentSlide.value > 0) {
    currentSlide.value--
  }

  updateSlidePosition()
}

const handleResize = () => {
  updateSlideWidth()
  updateSlidePosition()
}

const handleFilter = () => {
  currentPage.value = 1
  fetchAnimalList()
}

const resetFilter = () => {
  filterForm.species = ''
  filterForm.gender = ''
  currentPage.value = 1
  fetchAnimalList()
}

const handlePageChange = (page) => {
  currentPage.value = page
  fetchAnimalList()
}

const viewAnimalDetail = (id) => {
  router.push(`/animal/${id}`)
}

onMounted(() => {
  fetchAnimalList()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

watch(animalList, () => {
  nextTick(() => {
    initCarousel()
  })
})
</script>

<style scoped>
.home-page {
  /* START: 核心修改 - 为主页内容提供一个居中的、有最大宽度的容器 */

  /* -- 可调整区域 -- */
  --page-max-width: 1000px; /* 您可以在这里轻松调整最大宽度 */
  --page-padding-x: 20px;   /* 您可以在这里轻松调整左右间距 */
  /* -- 可调整区域结束 -- */

  width: 100%;
  max-width: var(--page-max-width);
  margin-left: auto;
  margin-right: auto;
  padding: 20px var(--page-padding-x);
  /* END: 核心修改 */
}

.background-image {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0; /* 确保背景图片在主布局之下 */
  overflow: hidden;

}
.background-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}



.section-title {
  margin-bottom: 10px;
  position: relative; /* 添加 position 属性 */
  z-index: 1; /* 设置 z-index 值，确保它大于背景图片的 z-index */
}

.animal-card {
  height: 100%;
  cursor: pointer;
}

.animal-row {
  row-gap: 20px;
}

.animal-image img {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 4px 4px 0 0;
}

.animal-card {
  /* //margin-top: 30px;
  //padding: 20px;
  //background-color: #f5f7fa;
  //zborder-radius: 8px; */
  overflow: hidden;
  margin-top: 30px;
  margin-bottom: 20px; /* 这是我们上次为了增加间距加的，保留 */
  padding: 20px;
  border-radius: 16px; /* 建议将圆角调大一些，毛玻璃效果更好看 */
  overflow: hidden;

  /* --- START: 毛玻璃效果核心代码 --- */

  /* 1. 设置一个半透明的背景色 */
  background-color: rgba(255, 255, 255, 0.5); /* 0.5是透明度，可调整 */

  /* 2. 对元素背后的内容应用模糊效果 */
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px); /* 兼容旧版 Safari 浏览器 */

  /* 3. (可选) 添加一个微妙的边框，让玻璃边缘更清晰 */
  border: 1px solid rgba(255, 255, 255, 0.2);

  /* 4. (可选) 替换原有的阴影，使用更柔和的阴影 */
  box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
}

.carousel-container {
  margin-bottom: 30px;
  position: relative;
  overflow: hidden;
  height: 400px;
  /* 半透明磨砂效果 */
  backdrop-filter: blur(10px); /* 磨砂效果，模糊程度为 10px */
  background-color: rgba(255, 255, 255, 0.5); /* 半透明背景，白色背景透明度为 50% */
}

.carousel-track {
  display: flex;
  transition: transform 0.5s ease;
}

.carousel-item {
  flex-shrink: 0;
  padding: 0 10px;
  box-sizing: border-box;
}

.carousel-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  margin-top: 5px;
}

.carousel-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px 0 rgba(0, 0, 0, 0.12);
}

.carousel-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.carousel-info {
  padding: 10px;
  text-align: center;
}

.animal-name {
  font-weight: bold;
  margin-bottom: 5px;
  color: #303133;
}

.animal-species {
  font-size: 0.9rem;
  color: #606266;
}

.carousel-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  gap: 15px;
}

.control-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border: 1px solid #dcdfe6;
  border-radius: 50%;
  background-color: white;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s ease;
  z-index: 1;
}

.control-btn:hover {
  background-color: #409EFF;
  color: white;
  border-color: #409EFF;
}

.control-btn:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.slide-indicators {
  display: flex;
  gap: 8px;
}

.slide-indicators span {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #dcdfe6;
  cursor: pointer;
  transition: all 0.3s ease;
}

.slide-indicators span.active {
  background-color: #409EFF;
  transform: scale(1.2);
}

.grabbing {
  cursor: grabbing;
}

.grabbing .carousel-track {
  cursor: grabbing;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 28px;
  color: #303133;
  margin-bottom: 10px;
}

.page-header p {
  font-size: 16px;
  color: #606266;
}

.filter-section {
  /* 保留我们之前为了增加间距添加的外边距 */
  margin-top: 20px;
  margin-bottom: 20px;

  padding: 20px;
  border-radius: 16px; /* 增大圆角以匹配轮播图的样式 */

  /* --- START: 毛玻璃效果核心代码 --- */
  background-color: rgba(255, 255, 255, 0.5);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
  /* --- END: 毛玻璃效果核心代码 --- */
}

.animal-list {
  margin-bottom: 20px;
}

.animal-card {
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.3s; /* 将 transform 改为 all，让阴影和边框变化也更平滑 */
  height: 100%; /* 之前为了对齐添加的，保留 */
  border-radius: 16px; /* 统一圆角 */

  /* --- START: 毛玻璃效果核心代码 --- */
  background-color: rgba(255, 255, 255, 0.5);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
  /* --- END: 毛玻璃效果核心代码 --- */
}

.animal-card:hover {
  transform: translateY(-5px);
}

.animal-image {
  height: 200px;
  overflow: hidden;
}

.animal-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.animal-info {
  padding: 15px 0 5px;
}

.animal-info h3 {
  margin-bottom: 10px;
  font-size: 18px;
}

.animal-info p {
  margin-bottom: 5px;
  font-size: 14px;
  color: #606266;
}

.pagination-container {
  text-align: center;
  margin-top: 30px;
}
.number{
  display: flex;
  justify-content: center;
}
</style>